﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Disposables;
using System.Linq;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Data;
using SoftSource.Common;
using SoftSource.Timecard.Entry.ViewModelInterfaces;
using SoftSource.Timecard.Web.Data;
using SoftSource.Reactive;

namespace SoftSource.Timecard.Entry.ViewModels
{
    public class EntryViewModel : IEntryViewModel, IDisposable
    {
        private CompositeDisposable compositeDisposable;

        public EntryViewModel()
        {
            this.compositeDisposable = new CompositeDisposable();

            this.Entries = new ObservableProperty<PagedCollectionView>();
            this.compositeDisposable.Add(this.Entries
                .Do(pcv => pcv.SortDescriptions.Add(new SortDescription(
                    ObjectReflection.GetPropertyName<EntryLog>(e => e.EntryDate),
                    ListSortDirection.Descending)))
                .Do(pcv => pcv.MoveCurrentToFirst())
                .Subscribe());
        }

        #region INotifyPropertyChanged Members
        
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
        }

        #endregion

        #region IEntryViewModelConsume Members

        public IObservableProperty<PagedCollectionView> Entries { get; private set; }

        public Func<IObservable<Unit>> SaveAll { get; set; }
        public Func<EntryLog, IObservable<Unit>> Save { get; set; }
        public Func<EntryLog, IObservable<Unit>> Delete { get; set; }
        public IObservable<Unit> Load { get; set; }
        public Func<DateTime, DateTime, IObservable<Unit>> LoadEntries { get; set; }
        public Func<EntryLog, Action, UIElement> CreateEditEntryEditorView { get; set; }
        public Func<EntryLog, EntryLog> Clone { get; set; }
        public Func<EntryLog, EntryLog> AddNew { get; set; }

        #endregion

        #region IEntryViewModelService Members

        private IEnumerable<EntryLog> entrySource;
        public IEnumerable<EntryLog> EntrySource
        {
            get { return this.entrySource; }
            set
            {
                this.entrySource = value;
                this.Entries.Value = new PagedCollectionView(this.entrySource);
            }
        }

        #endregion

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            this.compositeDisposable.Dispose();
            GC.SuppressFinalize(this);
        }

        #endregion

        ~EntryViewModel()
        {
            this.Dispose();
        }
    }
}
